<?php

namespace app\bancard\controller;

use app\common\lib\Broker;
use think\Controller;
use think\facade\Cache;
use app\common\validate\NewsValidate;
use app\bancard\model\News as NewsModel;
use think\facade\Log;

class Test extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $broker = new Broker(config('app.sso.sso_server'), config('app.sso.sso_broker_id'), config('app.sso.sso_broker_secret'));
        $broker->attach(true);
        $user = null;
        try {
            $user = $broker->getUserInfo();
        } catch (NotAttachedException $e) {
            header('Location: ' . $_SERVER['REQUEST_URI']);
            exit;
        } catch (SsoException $e) {
            $this->error($e->getMessage(), '');
        }
        if ($user) {
            // 有用户信息 先取本地session,等到用户$u
            $u = session('admin');
            if ($u) {
                if ($u['id'] != $user['id']) {
                    //替换新用户session
                    session('admin', $user);
                }
            } else {
                //设置本地session,新的$user进行登录
                session('admin', $user);
            }
        } else {
            //没有登录 清除session,跳转登录页
            session('admin', null);
        }

    }
    //首页
    public function index()
    {
        return $this->fetch();
    }

    public function lists()
    {

        $time1 = microtime(true);
        $memory1 = memory_get_usage();
        // ... 执行代码 ...


        $user_id = 1;
        $school_id = 1;
        $ntitle = request()->param('keywords');
        $title = isset($ntitle) ? $ntitle : '';
        $limit = request()->param('limit');
        $offset = request()->param('offset');
        $start = ($offset - 1) * $limit;
        $map = [
            'user_id' => $user_id,
            'school_id' => $school_id
        ];
        if ($title) {
            $count = db('news')->where($map)->whereLike('title', "%$title%")->count();
            $result = db('news')->where($map)->whereLike('title', "%$title%")->limit($start, $limit)->order('sort desc,id desc')->select();
        } else {
            $count = db('news')->where($map)->count();
            $result = db('news')->where($map)->limit($start, $limit)->order('sort desc,id desc')->select();
        }

        $time2 = microtime(true);
        $memory2 = memory_get_usage();
        $time = round($time2 - $time1, 4);
        $memory = round(($memory2 - $memory1) / 1024 / 1024, 4);
        //return compact('time', 'memory');
        $str = '耗时' . $time . '秒<br>';
        $str .= '内存: ' . $memory . '<br />';

        Log::info($str);

        return showTable(0, 'OK', $count, $result, 200);
    }

}